package com.micro.ai.gateway.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * Redis服务（响应式版本）
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class RedisService {

    @Autowired
    private ReactiveRedisTemplate<String, String> reactiveRedisTemplate;

    /**
     * 设置键值对
     */
    public Mono<Boolean> set(String key, String value, long timeout, java.util.concurrent.TimeUnit unit) {
        Duration duration = Duration.ofMillis(unit.toMillis(timeout));
        return reactiveRedisTemplate.opsForValue()
                .set(key, value, duration)
                .doOnSuccess(result -> log.debug("Redis SET: key={}, value={}, timeout={}", key, value, timeout))
                .doOnError(error -> log.error("Redis SET failed: key={}, error={}", key, error.getMessage()));
    }

    /**
     * 获取值
     */
    public Mono<String> get(String key) {
        return reactiveRedisTemplate.opsForValue()
                .get(key)
                .doOnSuccess(value -> log.debug("Redis GET: key={}, value={}", key, value))
                .doOnError(error -> log.error("Redis GET failed: key={}, error={}", key, error.getMessage()));
    }

    /**
     * 检查键是否存在
     */
    public Mono<Boolean> hasKey(String key) {
        return reactiveRedisTemplate.hasKey(key)
                .doOnSuccess(exists -> log.debug("Redis HASKEY: key={}, exists={}", key, exists))
                .doOnError(error -> log.error("Redis HASKEY failed: key={}, error={}", key, error.getMessage()));
    }

    /**
     * 删除键
     */
    public Mono<Boolean> delete(String key) {
        return reactiveRedisTemplate.delete(key)
                .map(count -> count > 0)
                .doOnSuccess(deleted -> log.debug("Redis DELETE: key={}, deleted={}", key, deleted))
                .doOnError(error -> log.error("Redis DELETE failed: key={}, error={}", key, error.getMessage()));
    }
}
